<template>
  <div class="verify-page container">
    <VerificationSection
      :is-logged-in="isLoggedIn"
      :records="records"
      :loading="loading"
      :error="error"
      :detail="detail"
      :detail-loading="detailLoading"
      @login="openLogin"
      @refresh="loadRecords"
      @view="handleView"
      @cancel="handleCancel"
    />
  </div>
</template>

<script setup>
import { computed, inject, onMounted, watch } from "vue";
import VerificationSection from "../components/VerificationSection.vue";
import { useVerificationStore } from "../store/verification";
import { useUserStore } from "../store/user";
import { message } from "../utils/message";

const verificationStore = useVerificationStore();
const userStore = useUserStore();
const appBridge = inject("appBridge", null);

const isLoggedIn = computed(() => userStore.isLoggedIn);
const records = computed(() => verificationStore.records);
const loading = computed(() => verificationStore.loading);
const error = computed(() => verificationStore.error);
const detail = computed(() => verificationStore.detail);
const detailLoading = computed(() => verificationStore.detailLoading);

const openLogin = () => {
  appBridge?.openLogin?.();
};

const loadRecords = async () => {
  if (!isLoggedIn.value) {
    verificationStore.clear();
    return;
  }
  try {
    await verificationStore.load({ page: 1, page_size: 10 });
  } catch (err) {
    message.error(err.message || "核实记录加载失败");
  }
};

const handleView = async id => {
  try {
    await verificationStore.loadDetail(id);
  } catch (err) {
    message.error(err.message || "获取详情失败");
  }
};

const handleCancel = async id => {
  if (!window.confirm("确认取消该核实单吗？")) return;
  try {
    await verificationStore.cancel(id);
    message.success("已取消");
  } catch (err) {
    message.error(err.message || "取消失败");
  }
};

onMounted(() => {
  loadRecords();
});

watch(isLoggedIn, () => {
  loadRecords();
});
</script>

<style scoped lang="scss">
.verify-page {
  padding-top: 32px;
  padding-bottom: 48px;
}
</style>
